package com.njupt.webapp.tags;

import java.util.List;

import javax.servlet.jsp.JspException;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import com.njupt.dao.BaseDao;

/**
 * 输入hql语句，执行改语句，存储查询结果。
 *
 */
public class HqlQueryForListTag extends HqlBaseTag{
	public Integer startIndex = 0;
	public Integer pageSize;
	public int doStartTag() throws JspException {
        String hqlx = (String) TagUtils.evaluate("hql",hql, String.class,this,pageContext);
        BaseDao baseDao = this.getBaseDao();
        //判断是否使用cache
        if( super.useCache ){
        	Cache cache = this.getCache();
            Element element = cache.get(hqlx);
            //如果cache中命中
            if( null != element ){
            	TagUtils.saveToContext(this,pageContext,scope, element.getObjectValue());
            }else{
            	//如果不命中
            	List<?> l = null;
	        	if(pageSize == null){
	        		l = baseDao.executeQuery(hqlx);
	        	}else{
	        		l = baseDao.queryByHql(hqlx,startIndex,pageSize);
	        	}
	        	//放入cache
	        	element = new Element(hqlx,l);
	        	cache.put(element);
	        	TagUtils.saveToContext(this,pageContext,scope,l);
            }
        }else{
        	//不使用cache
        	List<?> l = null;
        	if(pageSize == null){
        		l = baseDao.executeQuery(hqlx);
        	}else{
        		l = baseDao.queryByHql(hqlx,startIndex,pageSize);
        	}
        	TagUtils.saveToContext(this,pageContext,scope,l);
        }
        return super.doStartTag();
	}

	public Integer getStartIndex() {
		return startIndex;
	}
	public void setStartIndex(Integer startIndex) {
		this.startIndex = startIndex;
	}

	public Integer getPageSize() {
		return pageSize;
	}
	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}
}
